<template>
  <div>
    <div class="ccui-navigation" ref="navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回</el-button
      >
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item :to="{ path: '/' }">{{
          appName
        }}</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/powerManage/powerManageList' }"
          >权限管理</el-breadcrumb-item
        >
        <el-breadcrumb-item
          >成员维护<span class="ccui-curr-crumb" style="margin-left: 10px;">
            {{ roleName }}</span
          ></el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail2 ccui-clearfix">
      <div class="ccui-app-container-detail-body">
        <div
          class="ccui-advanced-search-wrapper ccui-clearfix"
          ref="advancedSearchWrapper"
        >
          <div class="ccui-search-wrapper ccui-clearfix">
            <!--普通搜索Begin-->

            <el-button
              size="mini"
              type="primary"
              icon="icon-ccui-add-sup"
              @click="handleAddMember"
              class="fright"
              >添加成员
            </el-button>
            <!--普通搜索End-->
          </div>
        </div>
        <div class="ccui-multifunctional-table-wrapper">
          <el-table
            ref="multipleTable"
            :data="tableData"
            :fit="true"
            :row-style="rowClass"
            :cell-style="cellStyle"
            border
            class="ccui-multifunctional-table"
            @select-all="handleCheckAllChange"
            @select="handleCheckChange"
            @selection-change="handleSelectionChange"
            max-height="20000"
          >
            <el-table-column
              type="selection"
              width="55"
              :selectable="filterCheck"
            />
            <el-table-column type="index" label="序号" fixed="left" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
                <!--{{ scope.$index + (pageNo - 1) * pageSize + 1 }}-->
              </template>
            </el-table-column>
            <el-table-column
              label="姓名"
              width="auto"
              prop="name"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <template v-for="(table, index) in fixedTableThead">
              <el-table-column
                v-if="table.checked"
                :fixed="table.fixed"
                :key="index"
                :label="table.label"
                :width="table.width"
                :prop="table.prop"
                :show-overflow-tooltip="true"
              >
                <template #default="{row}">
                  {{
                    table.prop === "orgName"
                      ? row.orgName + "/" + row.deptName
                      : row[table.prop]
                  }}
                </template>
              </el-table-column>
            </template>

            <el-table-column label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button
                  v-if="true"
                  size="mini"
                  type="text"
                  @click="handleDelete(scope.$index, scope.row)"
                  :disabled="ise && openId === scope.row.openId"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="ccui-table-footer" v-if="ifShowPage">
            <div v-show="isSelection" class="ccui-operation">
              <el-button size="mini" type="default" @click="handleDelSelected"
                >批量删除</el-button
              >
            </div>
            <div id="ccui-paging">
              <el-pagination
                :total="totalNum"
                :page-size="pageSize"
                :current-page="pageNo"
                :page-sizes="[10, 20, 50, 100, 200, 500]"
                prev-text="< 上一页"
                next-text="下一页 >"
                background
                layout="total, sizes, prev, pager, next, jumper"
                popper-class="ccui-paging-page-size-popper"
                @prev-click="handlePrev"
                @next-click="handleNext"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
              <el-button
                class="ccui-pagination-btn"
                size="mini"
                type="default"
                @click="handleSizeChange('none')"
                >确定
              </el-button>
            </div>
          </div>
        </div>

        <selectTree
          :isShow.sync="isShow"
          :requestSeachParams="requestSeachParams"
          :requestSeachFunction="requestSeachFunction"
          :requestTreeFunction="requestTreeFunction"
          :requestTreeParams="param"
          :setTreeICon="setTreeICon"
          :setSelectedIcon="setSelectedIcon"
          @selectedStaffSuccess="selectedStaffSuccess"
          :selectedData="selectedData"
          title="添加成员"
        >
          <div slot-scope="{ item }">
            <div :title="item.orderName" class="orgName">
              <i :class="setSeachIcon(item)" class="orgIcon"></i>
              <span>{{ item.abbrName }}</span>
            </div>
            <p class="orgFullName" :title="item.orgFullName">
              {{ item.orgFullName }}
            </p>
          </div>
        </selectTree>
      </div>
    </div>
  </div>
</template>

<script>
import { searchList } from "../api/process";
import { qryUnderOrg } from "../api/util.js";
import selectTree from "@/basa/components/selectTree";
import { deleteUser, getUserList, addUserList } from "../api/powerManage";
import getMenuaa from "../mixins/getMenu.js";
export default {
  name: "powerManageMemberMaintain",
  components: {
    selectTree
  },
  mixins: [getMenuaa],
  data() {
    return {
      ifShowPage: true,
      menu: [],
      ise: true,
      openId: "",
      appName: JSON.parse(sessionStorage.userDetal).agentName,
      requestTreeFunction: qryUnderOrg,
      requestSeachFunction: searchList,
      selectedData: [],
      requestSeachParams: {
        flag: 2,
        branchName: "",
        orgID: ""
      },
      isShow: false,
      roleId: this.$route.params.roleId, // 当前角色
      param: {
        isPrincipal: 1,
        parentId: "", // 全局 其他【此组件是本级及以下】
        flag: "2", // 0 公司 1 部门 2 成员
        isCompany: "1" // 是否公司 0否 1是
      },
      roleName: "",
      // 表格最大高度
      tableMaxHeight: 0,
      // 表格数据
      tableData: [],
      selectRow: [],
      // 表格命名
      tableName: this.tableList.powerManagemMemberMaintain,
      // 表格数据
      tableThead: [],
      // 锁定表格
      fixedTableThead: [
        {
          label: "性别",
          prop: "sex",
          width: "auto",
          checked: true,
          fixed: false
        },
        {
          label: "单位/部门",
          prop: "orgName",
          width: "500px",
          checked: true,
          fixed: false
        },
        {
          label: "职务",
          prop: "jobName",
          width: "200px",
          checked: true,
          fixed: false
        }
      ],

      demoKeys: [],
      // 弹框表格
      popoverShow: false,
      searchMoudle: {
        // 搜索模块数据
        isShow: false,
        searchData: {
          label: "姓名：",
          placeholder: "请输入姓名模糊查询",
          name: "userName"
        },
        inputSingle: "",
        input: "",
        value: "" // 简单搜索End
      },
      isSelection: false,
      isIndeterminate: false,
      checkAll: false,
      totalNum: 0,
      userName: "",
      pageSize: 10,
      pageNo: 1
    };
  },
  selectData(data) {
    this.selectRow = [];
    if (data.length > 0) {
      data.forEach((item, index) => {
        this.selectRow.push(this.tableData.indexOf(item));
      });
    }
  },
  watch: {
    popoverShow(value) {
      const that = this;
      if (value) {
        setTimeout(function() {
          document.body.addEventListener("click", that.popoverClose);
        }, 0);
      } else {
        document.body.removeEventListener("click", that.popoverClose);
      }
    }
  },
  created() {
    this.ise = ["100001", "100002"].includes(this.$route.params.roleId);
    this.openId = JSON.parse(localStorage.userInfo).openId;
    console.log(this.openId);
    console.log(this.$route.params.roleId);
    console.log(this.ise);
    this.roleId = this.$route.params.roleId;

    /** ****梁青竹 获取localStorage列表的条数Begin**********/
    let pageSizeObj = localStorage.getItem("amaMenberPageSize")
      ? JSON.parse(localStorage.getItem("amaMenberPageSize"))
      : null;
    this.pageSize =
      pageSizeObj && pageSizeObj[this.tableName]
        ? pageSizeObj[this.tableName]
        : this.pageSize; // 记住每页条数
    /** ****梁青竹 获取localStorage列表的条数End**********/
    // this.getRoleName();
    this.getList();
  },
  mounted() {
    // 自动获取表格高度
    this.$nextTick(() => {
      this.computeTableHeight();
    });
    // 浏览器调整大小时，表格高度实时改变
    window.onresize = () => {
      this.computeTableHeight();
    };
  },
  activated() {
    this.$store.dispatch("closeSidebarTemporary");
  },
  methods: {
    filterCheck(row) {
      console.log(row);
      if (this.ise && row.openId === this.openId) {
        return false;
      } else {
        return true;
      }
    },
    setSeachIcon(i) {
      let arr = [
        "icon-ccui-organization",
        "icon-ccui-unit",
        "icon-ccui-man-hollow",
        "icon-ccui-woman-hollow"
      ];
      let keyClass = "";
      if (i.orgType === "2") {
        if (i.sex === "0") {
          keyClass = "";
        } else {
          keyClass = arr[Number(i.orgType) + Number(i.sex) - 1];
        }
      } else {
        keyClass = arr[i.orgType];
      }

      return keyClass;
    },
    setTreeICon(h, node, data, store) {
      //  console.log(node,data,store)
      if (data.orgType === "2") {
        if (data.sex === "2") {
          return <i class="icon-ccui-woman-hollow is-leaf-org"></i>;
        } else if (data.sex === "1") {
          return <i class="icon-ccui-man-hollow is-leaf-org"></i>;
        } else {
          return <i class="icon-ccui-man-hollow is-leaf-org"></i>;
        }
      }
      if (data.orgType === "0") {
        return <i class="icon-ccui-organization is-leaf-org"></i>;
      }
      if (data.orgType === "1") {
        return <i class="icon-ccui-unit is-leaf-org"></i>;
      }
    },
    setSelectedIcon({ sex }) {
      if (sex === "2") {
        return "icon-ccui-woman-hollow";
      } else {
        return "icon-ccui-man-hollow";
      }
    },
    initData() {
      this.pageNo = 1;
      this.userName = "";
      this.searchMoudle.inputSingle = "";
      this.getList();
    },
    onSubmitSingle(obj) {
      this.pageNo = 1;
      this.userName = obj.userName;
      this.getList();
    },
    popoverClose() {
      this.popoverShow = false;
    },
    handlePopoverShow(column, event) {
      if (column.label === "set") {
        this.popoverShow = !this.popoverShow;
      }
    },
    // 根据返回状态显示不同的文字颜色
    cellStyle({ row, column, rowIndex, columnIndex }) {},

    handleSelectionChange(data) {
      this.selectData = data;
    },
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "rgba(255,232,195,1) " };
      }
    },
    handleGoEdit(index, row) {
      this.$router.push("/tmpl/demo/edit-demo/" + row.demoId);
    },
    handleDelete(index, row) {
      this.delList([{ openId: row.userId.split("@")[0], isShowLoading: true }]);
    },
    handleGoDetail(index, row) {
      this.$router.push(
        "/tmpl/demo/demo-detail/" + row.demoId + "/" + row.demoName
      );
    },
    /** *selectedStaff组件交互Begin***/
    handleAddMember() {
      this.requestSeachParams.orgID = this.$store.getters.userDetal.orgId + "";
      this.requestSeachParams.pageNo = 1;
      this.requestSeachParams.pageSize = 20;
      this.param.parentId = this.$store.getters.userDetal.partyRelaId;
      //this.chooseStaff.selectedData = []
      this.isShow = true;
    },
    selectedStaffSuccess(arr) {
      let arr2 = [];
      arr.forEach(n => {
        arr2.push({
          openId: n.userId.split("@")[0],
          autoCode: n.autoCode
        });
      });
      let obj = {
        userList: arr2,
        roleId: this.$route.params.roleId,
        isShowLoading: true
      };
      /* this.formdata.adminUserName = arr[0].name
this.formdata.adminUserId = arr[0].userId */
      /* this.$refs['ruleForm'].validateField('adminUserId') */
      addUserList(obj).then(res => {
        // let message = res.data.message || '添加成功'
        let message = this.tips.insertSuccessTip;
        this.$message({
          message: message,
          type: "success",
          duration: 3000,
          ccuiCustom: true,
          showClose: true,
          offset: document.body.clientHeight / 2 - 21
        });
        this.getList();
        this.getMenu();
      });
    },
    /** *selectedStaff组件交互End**/
    /** ******************大搜索区域Begin**********************/
    // 重置
    dataReset() {
      this.$refs.multiForm.fields.forEach(item => {
        if (item.prop === "advancedDatePicker") {
          item.$children[1].$el.children[0].children[1].children[0].value = "";
          item.$children[1].$el.children[0].children[2]
            .querySelectorAll(".el-range-input")
            .forEach(item => {
              item.value = "";
            });
        } else if (item.prop === "buyingunit") {
          item.$children[1].$el.children[0].children[0].value = "";
          item.$children[1].$children[0].state0 = "";
        }
      });
      this.multiDataToEnd = {};
      this.$refs.multiDataForm.forEach(item => {
        switch (Object.prototype.toString.call(item.searchData)) {
          case "[object String]":
            item.searchData = "";
            break;
          case "[object Boolean]":
            item.searchData = true;
            break;
          case "[object Array]":
            item.searchData = [];
            break;
        }
      });
    },
    clearSearchData(flag) {
      switch (flag) {
        case "single":
          this.searchMoudle.singleDataToEnd = {};
          break;
        case "multi":
          this.searchMoudle.multiDataToEnd = {};
          break;
      }
    },
    // 高级搜索展开按钮
    searchShow() {
      this.isShowVal = !this.isShowVal;
      this.searchMoudle.isShow = !this.searchMoudle.isShow;
    },
    // zh_下拉框点击事件
    handleColon(s) {
      this.$refs.select.$children[1].$children[0].$el.children[0].children[0].children[
        s - 1
      ].innerHTML = this.$refs.select.$children[1].$children[0].$el.children[0].children[0].children[
        s - 1
      ].innerHTML.replace("：", "");
    },
    // zh_下拉框点击事件
    handleSelectChange(value) {
      this.searchMoudle.options.forEach(item => {
        if (item.currentView === value) {
          switch (
            Object.prototype.toString.call(this.$refs.singleDataForm.searchData)
          ) {
            case "[object Array]":
              this.$refs.singleDataForm.searchData = [];
              break;
            case "[object String]":
              this.$refs.singleDataForm.searchData = "";
              break;
          }
        }
      });
    },
    // zh_下拉选项点击事件
    handleOptionClick(item, isSingle) {
      if (item.type === "select" || item.type === "radio-group") {
        this.searchMoudle.currentView = "my-select";
      } else if (item.type === "checkbox-group") {
        this.searchMoudle.currentView = "select-multi-create";
      } else {
        this.searchMoudle.currentView = item.type;
      }
      this.searchMoudle.currentPlaceholder = item.placeHolder;
    },
    // 搜索样式
    handleSearchMouseenter() {
      this.searchMoudle.btncolor.push("hover--btn");
    },
    handleSearchMouseleave() {
      this.searchMoudle.btncolor = [];
    },
    handleSearchMousedown() {
      this.searchMoudle.btncolor = [];
      this.searchMoudle.btncolor.push("mousedown--btn");
    },
    handleSearchMouseup() {
      this.searchMoudle.btncolor = [];
      this.searchMoudle.btncolor.push("hover--btn");
    },
    /** ******************大搜索区域End**********************/

    // 批量删除并刷新列表
    handleDelSelected() {
      console.log(this.idArrSelected);
      this.delList(this.idArrSelected);
    },
    handleExport() {
      console.log("导出", this.idArrSelected);
    },
    handlePrev() {
      console.log("上一页");
    },
    handleNext() {
      console.log("下一页");
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      // val !== 'none' && (this.pageSize = val)
      if (val !== "none") {
        /** ****梁青竹 存储localStorage列表的条数Begin**********/
        let pageSizeObj = localStorage.getItem("amaMenberPageSize")
          ? JSON.parse(localStorage.getItem("amaMenberPageSize"))
          : {};
        pageSizeObj[this.tableName] = val;
        localStorage.setItem("amaMenberPageSize", JSON.stringify(pageSizeObj));
        this.pageSize = val;
        /** ****梁青竹 存储localStorage列表的条数End**********/
      }
      this.getList();
    },
    handleCurrentChange(val) {
      // 跳转翻页都会调这个方法
      this.pageNo = val;
      this.getList();
    },
    // getRoleName() {
    //   // 请求角色名称
    //   let obj = {
    //     dictKey: Number(this.$route.params.roleId),
    //     code: "MEMBER_PRESET_ROLE"
    //   };
    //   getRoleNameApi(obj).then(res => {
    //     console.log(res);
    //     this.roleName = res.data.data.dicValue;
    //   });
    // },
    // 数据请求
    getList() {
      // 重置已选择的记录
      console.log(this.pageNo);
      const obj = {
        roleId: this.roleId,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        isShowPageLoading: true
      };
      getUserList(obj).then(res => {
        console.log(res);
        this.roleName = res.data.data.roleName;

        this.tableData = res.data.data.rows.map(item => {
          // item.sex = item.sex === 1 ? "男" : "女"
          if (item.sex === 2) {
            item.sex = "女";
          } else if (item.sex === 1) {
            item.sex = "男";
          } else {
            item.sex = "";
          }
          return item;
        });
        if (this.tableData.length === 0) {
          this.ifShowPage = false;
        } else {
          this.ifShowPage = true;
        }
        this.totalNum = res.data.data.recordsTotal;
        this.pageNo = res.data.data.pageNo === 0 ? 1 : res.data.data.pageNo;
        console.log(res);
        this.isSelection = false;
        console.log(this.totalNum, this.pageNo);
      });
      // .catch(e => {
      //     console.log(e)
      // })
    },
    delList(arr) {
      deleteUser({
        userList: arr,
        roleId: this.roleId, // 当前角色id 需要改
        isShowLoading: true,
        loadingMessage: "删除中,请稍等..."
      }).then(res => {
        console.log(res);
        if (res.data.code === "0") {
          this.$message({
            message: this.tips.deleteSuccessTip,
            type: "success",
            duration: 3000,
            ccuiCustom: true,
            showClose: true,
            offset: document.body.clientHeight / 2 - 21
          });
          this.getMenu();
        } else {
          this.$message({
            message: res.data.message,
            type: "error",
            duration: 3000,
            ccuiCustom: true,
            showClose: true,
            offset: document.body.clientHeight / 2 - 21
          });
        }

        // console.log( this.pageNo)
        // console.log(Math.ceil(this.totalNum / this.pageSize))
        let totalPages = Math.ceil(this.totalNum / this.pageSize);
        let prevPage = this.pageNo - 1 === 0 ? 1 : this.pageNo - 1;
        let inItemLengs = this.totalNum - (this.pageNo - 1) * this.pageSize;
        if (totalPages === this.pageNo && arr.length === inItemLengs) {
          this.pageNo = prevPage;
        }

        this.getList();
        this.isSelection = false;
      });
      // .catch(e => {
      //     this.$message({
      //         message: e,
      //         type: "error",
      //         duration: 3000,
      //         ccuiCustom: true,
      //         showClose: true,
      //         offset: document.body.clientHeight / 2 - 21
      //     })
      //     console.log(e)
      // })
    },
    handleCheckAllChange(val) {
      this.isIndeterminate = false;
      const arr = [];
      console.log(val);
      for (let i = 0; i < val.length; i++) {
        arr.push({ openId: val[i].userId.split("@")[0] });
      }
      console.log(arr);
      this.idArrSelected = arr;
      if (val.length) {
        this.isSelection = true;
      } else {
        this.isSelection = false;
      }
      if (typeof val === "boolean") {
        if (val) {
          this.toggleSelection(this.tableData);
        } else {
          this.toggleSelection([]);
        }
      } else {
        this.checkAll = val.length !== 0;
      }
    },
    handleCheckChange(val) {
      console.log(val);
      const arr = [];
      for (let i = 0; i < val.length; i++) {
        arr.push({ openId: val[i].userId.split("@")[0] });
      }
      this.idArrSelected = arr;
      console.log(this.idArrSelected);
      if (val.length) {
        this.isSelection = true;
      } else {
        this.isSelection = false;
      }
      console.log(val.length);
      if (val.length > 0 && val.length < 2) {
        this.isIndeterminate = true;
      } else if (val.length === 2) {
        this.checkAll = true;
        this.isIndeterminate = false;
      } else {
        this.checkAll = false;
        this.isIndeterminate = false;
      }
    },
    toggleSelection(rows) {
      this.$refs.multipleTable.clearSelection();
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      }
    },
    showPopoverPanel() {
      this.popoverShow = !this.popoverShow;
    },
    handleBack() {
      // 返回
      this.$router.push({ path: "/powerManage/powerManageList" });
    },
    // 计算表格高度方法
    computeTableHeight() {
      // 获取表格所占区域的总高度
      let appContainerHeight = document.documentElement.clientHeight - 160 - 40;
      // 获取搜索区域的高度
      let searchHeight = this.$refs.advancedSearchWrapper.clientHeight;
      // 获取面包屑高度
      let crumbsHeight = this.$refs.navigation.clientHeight;
      // 减去为表格所占高度，-70为距底边留白区域
      this.tableMaxHeight =
        appContainerHeight - searchHeight - crumbsHeight - 70 > 0
          ? appContainerHeight - searchHeight - crumbsHeight - 70
          : 0;
    }
  },
  computed: {
    /** 大搜索模块相关Begin**/
    span() {
      return 12;
    }
    /** *大搜索模块相关End**/
  }
};
</script>

<style lang="scss" scoped>
@import "@/config/styles/variables.scss";

.app-container {
  background: none !important;
}
.fright {
  float: right;
}
.over-flow {
  overflow: auto;
}
.el-table-content {
  height: auto;
  background-color: $--color-white;
  padding: 20px;
  box-sizing: border-box;
}
.ccui-table-footer {
  margin-bottom: 20px;
}
/deep/ .el-table__fixed-right {
  height: auto;
}
.orgName {
  line-height: 18px;
}
.orgName span {
  font-size: 13px;
  color: #4a4a4a;
}
.orgFullName {
  line-height: 18px;
  margin-top: 5px;
  font-size: 13px;
  color: #999999;
  margin-left: 17px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.orgIcon {
  color: #0089ef;
  margin-right: 5px;
}
</style>
